﻿Imports System.Data.SqlClient
Imports Suprema
Public Class frmAltaHuellasUsuarios
    Private m_ScannerManager As UFScannerManager
    Private m_Scanner As UFScanner
    Private m_Matcher As UFMatcher
    Private m_Database As UFDatabase
    Private m_strError As String
    Private m_Serial As Integer
    Private m_UserID As String
    Private m_FingerIndex As Integer
    Private m_Template1 As Byte()
    Private m_Template1Size As Integer
    Private m_Template2 As Byte()
    Private m_Template2Size As Integer
    Private m_Memo As String
    '
    Private Const MAX_USERID_SIZE As Integer = 50
    Private Const MAX_TEMPLATE_SIZE As Integer = 1024
    Private Const MAX_MEMO_SIZE As Integer = 100
    '
    Private Const DATABASE_COL_SERIAL As Integer = 0
    Private Const DATABASE_COL_USERID As Integer = 1
    Private Const DATABASE_COL_FINGERINDEX As Integer = 2
    Private Const DATABASE_COL_TEMPLATE1 As Integer = 3
    Private Const DATABASE_COL_TEMPLATE2 As Integer = 4
    Private Const DATABASE_COL_MEMO As Integer = 5
    Private Sub frmAltaHuellasUsuarios_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        ToolStrip1.Cursor = Cursors.Hand
        ToolStrip1.RenderMode = System.Windows.Forms.ToolStripRenderMode.System

        m_ScannerManager = New UFScannerManager(Me)
        m_Scanner = Nothing
        m_Matcher = Nothing
        m_Database = Nothing

        m_Template1 = New Byte(MAX_TEMPLATE_SIZE) {}
        m_Template2 = New Byte(MAX_TEMPLATE_SIZE) {}

        lvDatabaseList.Columns.Add("Serial", 50, HorizontalAlignment.Left)
        lvDatabaseList.Columns.Add("Usuario", 120, HorizontalAlignment.Left)
        lvDatabaseList.Columns.Add("Nombre", 200, HorizontalAlignment.Left)
       

        cbScanTemplateType.SelectedIndex = 0
        CargaUsuarios()
        Iniciar()


    End Sub

    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
    Sub CargaUsuarios()

        lstUsuarios.Items.Clear()

        Dim cnconn As New SqlConnection
        cnconn.ConnectionString = InitialConnection
        Dim strSql As String = ""
        cnconn.Open()
        Dim cmdBuscar As New SqlCommand
        cmdBuscar.Connection = cnconn

        strSql = "SELECT Nombre FROM Usuarios where IdUsuario>1"


        cmdBuscar.CommandText = strSql
        Dim rdBuscar As SqlDataReader
        rdBuscar = cmdBuscar.ExecuteReader

        Do While rdBuscar.Read()
            lstUsuarios.Items.Add(rdBuscar("Nombre").ToString.Trim)
        Loop
    End Sub
    Sub Iniciar()
        '==========================================================================='
        ' Initilize scanners
        '==========================================================================='
        Dim ufs_res As UFS_STATUS
        Dim nScannerNumber As Integer

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Init()
        Windows.Forms.Cursor.Current = Me.Cursor
        If (ufs_res = UFS_STATUS.OK) Then
            tbxMessage.AppendText("Conexión del scanner: Correcta" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            tbxMessage.AppendText("Conexión del scanner: " & m_strError & vbNewLine)
            Exit Sub
        End If

        nScannerNumber = m_ScannerManager.Scanners.Count
        'tbxMessage.AppendText("UFScanner GetScannerNumber: " & nScannerNumber & vbNewLine)

        If (nScannerNumber = 0) Then
            tbxMessage.AppendText("No hay scanners disponibles" & vbNewLine)
            Exit Sub
        Else
            tbxMessage.AppendText("El primer scanner será usado" & vbNewLine)
        End If

        m_Scanner = m_ScannerManager.Scanners(0)
        '==========================================================================='

        '==========================================================================='
        ' Open database
        '==========================================================================='
        Dim ufd_res As UFD_STATUS

        m_Database = New UFDatabase()

        ' Generate connection string
        Dim DataSource As String
        Dim Connection As String
        '
        'DataSource = "UFDatabase.mdb"
        '
        'tbxMessage.AppendText("Select a database file" & vbNewLine)
        'Dim dlg As OpenFileDialog = New OpenFileDialog()
        'dlg.FileName = "UFDatabase.mdb"
        'dlg.Filter = "Database Files (*.mdb)|*.mdb"
        'dlg.DefaultExt = "mdb"
        'Dim res As DialogResult = dlg.ShowDialog()
        'If (res <> Windows.Forms.DialogResult.OK) Then
        'Exit Sub
        'End If

        DataSource = CitraInicial & "\UFDatabase.mdb"
        '
        Connection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & DataSource & ";"

        ' Open database
        ufd_res = m_Database.Open(Connection, "", "")
        If (ufd_res = UFD_STATUS.OK) Then
            tbxMessage.AppendText("Apertura de la base de datos: Correcta" & vbNewLine)
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Apertura de la base de datos: " & m_strError & vbNewLine)
            Exit Sub
        End If

        UpdateDatabaseList()
        '==========================================================================='

        '==========================================================================='
        ' Create matcher
        '==========================================================================='
        m_Matcher = New UFMatcher()
        '==========================================================================='
    End Sub
    Sub Terminar()
        '==========================================================================='
        ' Uninit scanner module
        '==========================================================================='
        Dim ufs_res As UFS_STATUS

        Windows.Forms.Cursor.Current = Cursors.WaitCursor
        ufs_res = m_ScannerManager.Uninit()
        Windows.Forms.Cursor.Current = Me.Cursor

        If (ufs_res = UFS_STATUS.OK) Then
            tbxMessage.AppendText("UFScanner Uninit: OK" & vbNewLine)
        Else
            UFScanner.GetErrorString(ufs_res, m_strError)
            tbxMessage.AppendText("UFScanner Uninit: " & m_strError & vbNewLine)
        End If
        '==========================================================================='

        '==========================================================================='
        ' Close database
        '==========================================================================='
        If (Not Equals(m_Database, Nothing)) Then
            Dim ufd_res As UFD_STATUS

            ' Close database
            ufd_res = m_Database.Close()
            If (ufd_res = UFD_STATUS.OK) Then
                tbxMessage.AppendText("UFDatabase Close: OK" & vbNewLine)
            Else
                UFDatabase.GetErrorString(ufd_res, m_strError)
                tbxMessage.AppendText("UFDatabase Close: " & m_strError & vbNewLine)
            End If
        End If

        lvDatabaseList.Items.Clear()
    End Sub
    Private Sub UpdateDatabaseList()
        If (Equals(m_Database, Nothing)) Then
            Exit Sub
        End If

        Dim ufd_res As UFD_STATUS
        Dim DataNumber As Integer
        Dim i As Integer

        ufd_res = m_Database.GetDataNumber(DataNumber)
        If (ufd_res = UFD_STATUS.OK) Then
            tbxMessage.AppendText("Registros de la base de datos: " & DataNumber & vbNewLine)
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Registros de la base de datos: " & m_strError & vbNewLine)
            Exit Sub
        End If

        lvDatabaseList.Items.Clear()

        For i = 0 To DataNumber - 1
            ufd_res = m_Database.GetDataByIndex(i, m_Serial, m_UserID, m_FingerIndex, m_Template1, m_Template1Size, m_Template2, m_Template2Size, m_Memo)
            If (ufd_res <> UFD_STATUS.OK) Then
                UFDatabase.GetErrorString(ufd_res, m_strError)
                tbxMessage.AppendText("Indice de datos: " & m_strError & vbNewLine)
                Exit Sub
            End If
            AddRow(m_Serial, m_UserID)
        Next
    End Sub
    Private Sub AddRow(ByVal Serial As Integer, ByVal UserID As String)
        Dim listItem As ListViewItem
        listItem = lvDatabaseList.Items.Add(Convert.ToString(Serial))
        listItem.SubItems.Add(UserID)
        listItem.SubItems.Add(BuscarStrDatoInicial("Select NombreCompleto From Usuarios WHERE Nombre='" & UserID & "'"))
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
    Private Function ExtractTemplate(ByRef Template As Byte(), ByRef TemplateSize As Integer) As Boolean
        Dim ufs_res As UFS_STATUS
        Dim EnrollQuality As Integer

        m_Scanner.ClearCaptureImageBuffer()

        tbxMessage.AppendText("Colocar dedo índice" & vbNewLine)

        TemplateSize = 0
        Do
            ufs_res = m_Scanner.CaptureSingleImage()
            If (ufs_res <> UFS_STATUS.OK) Then
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Capturando imágen: " & m_strError & vbNewLine)
                ExtractTemplate = False
                Exit Function
            End If

            DrawCapturedImage(m_Scanner)

            ufs_res = m_Scanner.Extract(Template, TemplateSize, EnrollQuality)
            If (ufs_res = UFS_STATUS.OK) Then
                tbxMessage.AppendText("Extracción de imagen: OK" & vbNewLine)
                Exit Do
            Else
                UFScanner.GetErrorString(ufs_res, m_strError)
                tbxMessage.AppendText("Extracción de imagen: " & m_strError & vbNewLine)
            End If
        Loop

        ExtractTemplate = True
    End Function
    Private Sub DrawCapturedImage(ByRef Scanner As UFScanner)
        Dim g As Graphics = pbImageFrame.CreateGraphics()
        Dim rect As Rectangle = New Rectangle(0, 0, pbImageFrame.Width, pbImageFrame.Height)
        Dim Resolution As Integer
        Try
            '
            'Scanner.DrawCaptureImageBuffer(g, rect, cbDetectCore.Checked);
            '
            Dim bitmap As Bitmap = Nothing
            Scanner.GetCaptureImageBuffer(bitmap, Resolution)
            pbImageFrame.Image = bitmap
        Finally
            g.Dispose()
        End Try
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        

        If lstUsuarios.Text = "" Then
            MsgBox("Debes seleccionar un usuario", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        Dim IdUser As Integer = BuscarIntDatoBiometria("SELECT Serial FROM fingerprints WHERE UserID='" & lstUsuarios.Text.Trim & "'")
        If IdUser > 0 Then
            MsgBox("El usuario ya tiene una huella asignada", MsgBoxStyle.Exclamation, "Aviso")
            Exit Sub
        End If

        If (Not ExtractTemplate(m_Template1, m_Template1Size)) Then
            Exit Sub
        End If
        'Dim dlg As UserInfoForm = New UserInfoForm(False)
        Dim ufd_res As UFD_STATUS

        tbxMessage.AppendText("Ingresar datos" & vbNewLine)
        'dlg.ShowDialog(Me)
        'If (dlg.DialogResult <> Windows.Forms.DialogResult.OK) Then
        'tbxMessage.AppendText("User data input is cancelled by user" & vbNewLine)
        'Exit Sub
        'End If

        ufd_res = m_Database.AddData(lstUsuarios.Text.Trim, Convert.ToInt32(2), m_Template1, m_Template1Size, Nothing, 0, "MEMO")
        If (ufd_res <> UFD_STATUS.OK) Then
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("Inserción de datos: " & m_strError & vbNewLine)
        Else
            cbScanTemplateType.Enabled = False
        End If

        UpdateDatabaseList()
    End Sub

    Private Sub ToolStripButton1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Terminar()
        Close()
    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
        Dim ufd_res As UFD_STATUS
        Dim Serial As Integer

        If (lvDatabaseList.SelectedIndices.Count = 0) Then
            tbxMessage.AppendText("Select data" & vbNewLine)
            Exit Sub
        Else
            Serial = Convert.ToInt32(lvDatabaseList.SelectedItems(0).SubItems(DATABASE_COL_SERIAL).Text)
        End If

        ufd_res = m_Database.RemoveDataBySerial(Serial)
        If (ufd_res = UFD_STATUS.OK) Then
            tbxMessage.AppendText("UFDatabase RemoveDataBySerial: OK" & vbNewLine)
            UpdateDatabaseList()
        Else
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("UFDatabase RemoveDataBySerial: " & m_strError & vbNewLine)
        End If
    End Sub
    Private Sub cbScanTemplateType_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        ' template type 2001,2002,2003

        If (m_Scanner Is Nothing) Then
            tbxMessage.AppendText("Select data" & vbNewLine)
            Exit Sub
        End If


        Select Case cbScanTemplateType.SelectedIndex

            Case 0
                m_Scanner.nTemplateType = 2001
            Case 1
                m_Scanner.nTemplateType = 2002
            Case 2
                m_Scanner.nTemplateType = 2003

        End Select
    End Sub

    Private Sub btnEnroll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If (Not ExtractTemplate(m_Template1, m_Template1Size)) Then
            Exit Sub
        End If

        'Dim dlg As UserInfoForm = New UserInfoForm(False)
        Dim ufd_res As UFD_STATUS

        tbxMessage.AppendText("Input user data" & vbNewLine)
        'dlg.ShowDialog(Me)
        'If (dlg.DialogResult <> Windows.Forms.DialogResult.OK) Then
        'tbxMessage.AppendText("User data input is cancelled by user" & vbNewLine)
        'Exit Sub
        'End If

        ufd_res = m_Database.AddData("ADMINISTRADOR", Convert.ToInt32(2), m_Template1, m_Template1Size, Nothing, 0, "MEMO")
        If (ufd_res <> UFD_STATUS.OK) Then
            UFDatabase.GetErrorString(ufd_res, m_strError)
            tbxMessage.AppendText("UFDatabase AddData: " & m_strError & vbNewLine)
        Else
            cbScanTemplateType.Enabled = False
        End If

        UpdateDatabaseList()
    End Sub

    Private Sub ToolStripButton4_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton4.Click
        pbImageFrame.Image = Nothing

    End Sub

    Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub
End Class